<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 用户
 *
 * @icon fa fa-users
 */
class Users extends Backend {

    /**
     * Users模型对象
     * @var \app\admin\model\Users
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Users;
    }

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
//            $otherwhere[] = ['referee_id', '=', $this->iAdminId];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                //获取配置
//                $config_key = 'xiangguanpeizhi';
//                $configInfo = \think\Db::name('configure')->where(['key' => $config_key])->find();
//                $configValue = json_decode($configInfo['desc'],TRUE);
//                $val['referee_price'] = $val['finish_task_num'] * floatval($configValue['rakeback_rate']);
                foreach ($list as &$val) {
                    $wallet_info = Db::name('wallet')->where(['user_id' => $val['user_id']])->find();
                    $val['balance'] = $wallet_info['balance'];
                    $val['scort_sum'] = Db::name('score_log')->where(['user_id' => $val['user_id'], 'change_type' => 0])->sum('change_amount');
                    $val['recharge_sum'] = Db::name('wallet_log')->where(['wallet_id' => $wallet_info['wallet_id'], 'change_type' => 0, 'change_matters' => 1])->sum('change_amount');
                    $val['consume_sum'] = Db::name('order')->where(['user_id' => $val['user_id'], 'type' => 1, 'is_pay' => 1, 'status' => 10])->sum('pay_price');
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids) {
        $row = $this->model->get(['user_id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $wallet_info = Db::name('wallet')->where(['user_id' => $row['user_id']])->find();
        $row['wallet_id'] = $wallet_info['wallet_id'];
        $row['balance'] = $wallet_info['balance'];
        $row['order_num'] = Db::name('order')->where(['user_id' => $row['user_id'], 'type' => 1, 'is_pay' => 1, 'status' => 10])->count();
        $row['scort_sum'] = Db::name('score_log')->where(['user_id' => $row['user_id'], 'change_type' => 0])->sum('change_amount');
        $row['recharge_sum'] = Db::name('wallet_log')->where(['wallet_id' => $wallet_info['wallet_id'], 'change_type' => 0, 'change_matters' => 1])->sum('change_amount');
        $row['consume_sum'] = Db::name('order')->where(['user_id' => $row['user_id'], 'type' => 1, 'is_pay' => 1, 'status' => 10])->sum('pay_price');

        $this->view->assign("detail", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function updatestatus() {
        $user_id = input('ids');
        $userInfo = \think\Db::name('users')->where(['user_id' => $user_id])->find();
        if (!$userInfo) {
            $this->error('无该用户');
        }
        if ($userInfo['status'] == 1) {
            $status = 0;
        } else {
            $status = 1;
        }
        $data['status'] = $status;
        db('users')->where(['user_id' => $user_id])->update($data);
        $this->success();
    }

    public function getWalletList() {
        //设置过滤方法
        $this->model = new \app\admin\model\WalletLog;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as &$row) {
                if ($row['order_id'] != 0) {
                    $row['order_no'] = db('order')->where(['order_id' => $row['order_id']])->value('order_no');
                }
            }
            unset($row);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }

    public function getScoreList() {
        //设置过滤方法
        $this->model = new \app\admin\model\ScoreLog;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as &$row) {
                if ($row['order_id'] != 0) {
                    $row['order_no'] = db('order')->where(['order_id' => $row['order_id']])->value('order_no');
                }
            }
            unset($row);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }

    public function getOrderList() {
        //设置过滤方法
        $this->model = new \app\admin\model\Order;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as &$row) {
                if ($row['user_box_id'] != 0) {
                    $row['order_no'] = db('order')->where(['order_id' => $row['order_id']])->value('order_no');
                }
            }
            unset($row);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }

    public function getGoodsList() {
        $id = $this->request->param('ids');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, [], ['total_price' => 'ubg.box_goods_id', 'createtime' => 'o.createtime']);
            $total = db('order')
                    ->alias('o')
                    ->join('order_goods og', 'o.order_id = og.order_id')
                    ->join('user_box_goods ubg', 'og.box_goods_id = ubg.box_goods_id')
                    ->join('goods g', 'ubg.goods_id=g.goods_id')
                    ->where($where)
                    ->where('o.type', 1)
                    ->where('o.status', 10)
                    ->where('o.user_id', $id)
                    ->group('g.goods_id')
                    ->select();

            $total = count($total);

            $list = db('order')
                    ->alias('o')
                    ->field('g.goods_id,g.goods_title,g.brand_id,g.cate_id,sum(og.buy_num) as buy_num,sum(og.buy_num*ubg.selling_price) as total_price')
                    ->join('order_goods og', 'o.order_id = og.order_id')
                    ->join('user_box_goods ubg', 'og.box_goods_id = ubg.box_goods_id')
                    ->join('goods g', 'ubg.goods_id=g.goods_id')
                    ->where($where)
                    ->where('o.user_id', $id)
                    ->group('g.goods_id');


            $sort1 = $this->request->get("sort", "id");
            $order1 = $this->request->get("order", "DESC");

            if ($sort1 == 'buy_num') {
                $list->orderRaw('sum(og.buy_num) ' . $order1);
            } else if ($sort1 == 'total_price') {
                $list->orderRaw('sum(og.buy_num*ubg.selling_price) ' . $order1);
            } else {
                $list->order($sort, $order);
            }

            $list = $list->limit($offset, $limit)
                    ->select();


            $list = collection($list)->toArray();
            if ($list) {
                $i = $offset + 1;
                foreach ($list as &$val) {
                    $val['no'] = $i;
                    $val['brand_title'] = db('goods_brand')->where(['brand_id' => $val['brand_id']])->value('brand_title');
                    $val['cate_title'] = db('goods_cate')->where(['cate_id' => $val['cate_id']])->value('cate_title');
                    $i++;
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }

    public function updateWallet() {
        $wallet_id = input('wallet_id', 0);
        $type = input('type', 0, 'intval');
        $price = input('price', 0);
        $remark = input('remark');

        $arrLogData['wallet_id'] = $wallet_id;
        $arrLogData['change_type'] = $type;
        $arrLogData['change_matters'] = 3;
        $arrLogData['change_amount'] = $price;
        $arrLogData['remark'] = $remark;
        db('wallet_log')->insert($arrLogData);
        if ($type == 0) {
            db('wallet')->where(['wallet_id' => $wallet_id])->setInc('balance', $price);
        } else {
            db('wallet')->where(['wallet_id' => $wallet_id])->setDec('balance', $price);
        }
        $this->success('操作成功');
    }

    public function updateScore() {
        $user_id = input('user_id', 0);
        $type = input('type', 0, 'intval');
        $num = input('num', 0);
        $remark = input('remark');

        $arrLogData['user_id'] = $user_id;
        $arrLogData['change_type'] = $type;
        $arrLogData['change_matters'] = 3;
        $arrLogData['change_amount'] = $num;
        $arrLogData['remark'] = $remark;
        db('score_log')->insert($arrLogData);
        if ($type == 0) {
            db('users')->where(['user_id' => $user_id])->setInc('score', $num);
        } else {
            db('users')->where(['user_id' => $user_id])->setDec('score', $num);
        }
        $this->success('操作成功');
    }

}
